/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/


#include "MkRtmp/MkRtmpPlayer.h"
#include "MkEvent/MkEvent.h"
#include "MkEvent/MkEventPool.h"
#include "MkEvent/MkTimer.h"
#include "MkUtil/MkLog.h"
#include <signal.h>

CMkTimer *g_pTimer = nullptr;
CMkEventPool* g_pPool = nullptr;
CMkRtmpPlayer* g_pReceiver = nullptr;
void SigHandle(int sig)
{
    if (sig == SIGINT) {
        g_pTimer->LoopBreak();
    }
};

//#include "MkLibRtmp/MkRtmpReciver.h"
//void LibRtmpTest()
//{
//    MkString RtmpUrl = "rtmp://192.168.1.176/live/test5";
//     //RtmpUrl = "rtmp://192.168.100.120:51935/live/test5";
//    CMkRtmpReciver *pRtmp = CMkRtmpReciver::CreateNew(RtmpUrl, [](MkEsPacket &Packet) {
//        return NoneError;
//    });
//    pRtmp->Init();
//    while (1)
//    {
//        CMkThread::ThreadSleep(1000);
//    }
//}

int main(int argc, char ** argv)
{

#ifdef _WIN32
    WSADATA WSAData;
    WSAStartup(0x101, &WSAData);
#else
    //signal(SIGPIPE, SIG_IGN);  //ignore sigpipe
    //signal(SIGPIPE, SIG_IGN);
    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set, SIGPIPE);
    sigprocmask(SIG_BLOCK, &set, NULL);
#endif
    //LibRtmpTest();

    //MkLogInitLevel("http_client", TO_FILE);
    MkLogChangeLevel(LOG_DEBUG);
    signal(SIGINT, SigHandle);// 设置退出信号
    CMkEventPool Pool;
    g_pPool = &Pool;
    Pool.Start(1);
    CMkTimer Timer;
    g_pTimer = &Timer;
    FILE *fp = fopen("1.dat", "wb");
    MkString RtmpUrl = "rtmp://127.0.0.1/file/aa.264";
    //RtmpUrl = "rtmp://192.168.100.120:51935/live/test5";
    g_pReceiver = new CMkRtmpPlayer(Pool.GetFreeEvent(), &Timer, [fp](CMkTcpClient* pClient) {
        fclose(fp);
        MkDelete(pClient);
        g_pReceiver = nullptr;
        g_pTimer->LoopBreak();
        return NoneError;
    });
    g_pReceiver->StartMediaSource(RtmpUrl, [](CMkMediaSource* pMediaSource, Uint32 ErrorCode) {
        return NoneError;
    }, [fp](const MkEsPacket& EsPacket, const CMkVideoParam& VideoParam, const CMkAudioParam& AudioParam) {
        if (MkCodecCavs > EsPacket.CodecType) {
            MkListBuffer::const_iterator it = EsPacket.BufferList.GetBufferList().begin();
            for (; it != EsPacket.BufferList.GetBufferList().end(); it++) {
                fwrite(&NaluStartCode, 1, 4, fp);
                fwrite(it->GetBuffer(), 1, it->GetLength(), fp);
            }
        }
        return NoneError;
    });
    Timer.Dispatch();
    if (g_pReceiver) {
        g_pReceiver->Close();
        CMkThread::ThreadSleep(1000);
    }
    Pool.Stop();
#ifdef _WIN32
    WSACleanup();
#endif
    return 0;
}
